﻿using DrawTools.Tools;
using DrawTools.Utils;
using LS.DicomViewer.ViewModels;
using Microsoft.Win32;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using Path = System.IO.Path;

namespace LS.DicomViewer
{
    /// <summary>
    /// DicomViewer.xaml 的交互逻辑
    /// </summary>
    public partial class ImageViewer : UserControl
    {
        #region 变量/属性

        public static readonly DependencyProperty ImageFileProperty = DependencyProperty.Register("ImageFile", typeof(string), typeof(ImageViewer), new PropertyMetadata(string.Empty, async (a, e) => await ((ImageViewer)a).ViewModel.Load(e.NewValue.ToString())));
        /// <summary>
        /// Dicom文件
        /// </summary>
        public string ImageFile { get => (string)this.GetValue(ImageFileProperty); set => this.SetValue(ImageFileProperty, value); }


        public static readonly DependencyProperty AutoSaveDrawDataProperty = DependencyProperty.Register("AutoSaveDrawData", typeof(bool), typeof(ImageViewer), new PropertyMetadata(false));
        /// <summary>
        /// 当图片切换时是否自动保存画图数据
        /// </summary>
        public bool AutoSaveDrawData { get => (bool)this.GetValue(AutoSaveDrawDataProperty); set => this.SetValue(AutoSaveDrawDataProperty, value); }

        public static System.Windows.Media.Color? ToolBarColor { get; set; }
        /// <summary>
        ///  dicom是否在处理中 
        /// </summary>
        public event Action<bool> IsBusyChanged;

        internal ImageViewModel ViewModel => this.mainPanel.DataContext as ImageViewModel;

        #endregion

        public ImageViewer()
        {
            var dic = new ResourceDictionary();
            try
            {
                dic.Source = new Uri("pack://application:,,,/HandyControl;component/Themes/SkinDark.xaml");
                this.Resources.MergedDictionaries.Add(dic);
            }
            catch { }
            try
            {
                dic.Source = new Uri("pack://application:,,,/HandyControl;component/Themes/Theme.xaml");
                this.Resources.MergedDictionaries.Add(dic);
            }
            catch { }
            try
            {
                dic.Source = new Uri("pack://application:,,,/DrawTools;component/Themes/generic.xaml");
                this.Resources.MergedDictionaries.Add(dic);
            }
            catch { }

            InitializeComponent();

            DpiHelper.GetDpiFromVisual(this);

            color_picker.SelectedColorChanged += delegate { this.drawCanvas.Brush = color_picker.SelectedBrush; btn_color.IsChecked = false; };
            color_picker.Canceled += delegate { btn_color.IsChecked = false; };

            this.toolbar.AddHandler(RadioButton.CheckedEvent, new RoutedEventHandler(OnDrawToolChecked));


            if (ToolBarColor != null)
            {
                this.toolbar.Background = new System.Windows.Media.SolidColorBrush(ToolBarColor.Value);
            }
        }

        #region 事件

        private void btn_clear_Click(object sender, RoutedEventArgs e)
        {
            drawCanvas.Clear();
        }
        private void OnDrawToolChecked(Object sender, RoutedEventArgs e)
        {
            if (e.Source is RadioButton btn && btn.Tag is String typeStr)
                drawCanvas.DrawingToolType = (DrawToolType)Enum.Parse(typeof(DrawToolType), typeStr);
        }

        #endregion

        #region 公有方法

        /// <summary>
        /// 从指定目录中加载影像文件，默认显示第一张影像文件
        /// </summary>
        /// <param name="path"></param>
        public async void LoadImageFile(string path)
        {
            if (AutoSaveDrawData)
            {
                var filePath = ViewModel.ImageFilePath + ".xml";
                this.SaveDrawDataToFile(filePath);
            }
            ClearDrawLines();
            await ViewModel.Load(path);
            var newFilePathDrawData = path + ".xml";
            if (File.Exists(newFilePathDrawData))
            {
                this.LoadDrawDataFromFile(newFilePathDrawData);
            }
        }
        /// <summary>
        /// 设置当前图片
        /// </summary>
        /// <param name="bitmap"></param>
        public void SetBitmapSource(BitmapSource bitmap)
        {
            ViewModel.ImageSource = bitmap;
        }
        /// <summary>
        /// 加载画图数据
        /// </summary>
        /// <param name="xmlData"></param>
        public void SetDrawData(string xmlData)
        {
            this.drawCanvas.SetDrawDataFromXml(xmlData.TrimStart());
        }
        /// <summary>
        /// 加载画图数据文件
        /// </summary>
        /// <param name="xmlDataFile"></param>
        public void LoadDrawDataFromFile(string xmlDataFile)
        {
            this.drawCanvas.LoadDrawDataFromFile(xmlDataFile);
        }
        /// <summary>
        /// 清除当前页面的画线
        /// </summary>
        public void ClearDrawLines()
        {
            this.drawCanvas.Clear();
        }

        /// <summary>
        /// 获取画图数据(Xml格式)
        /// </summary>
        /// <returns></returns>
        public string GetDrawData()
        {
            return this.drawCanvas.GetDrawDataToXml();
        }
        /// <summary>
        /// 获取图片
        /// </summary>
        /// <returns></returns>
        public BitmapSource? GetBitmapSource()
        {
            var backgroundImage = this.drawViewer.BackgroundImage;
            var frame = this.drawCanvas.ToBitmapFrame(backgroundImage.PixelWidth, backgroundImage.PixelHeight, backgroundImage);

            if (frame == null) return null;
            var folder = Path.Combine(Environment.CurrentDirectory, "Images");
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory("Images");
            }
            return ImageHelper.GetBitmapSource(".jpeg", frame);
        }
        /// <summary>
        /// 保存图片到指定文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public string SaveBitmapToFile(string filePath = null)
        {
            var backgroundImage = this.drawViewer.BackgroundImage;
            var frame = this.drawCanvas.ToBitmapFrame(backgroundImage.PixelWidth, backgroundImage.PixelHeight, backgroundImage);
            if (frame == null) return null;
            var folder = Path.Combine(Environment.CurrentDirectory, "Images");
            if (string.IsNullOrEmpty(filePath))
            {
                var dlg = new SaveFileDialog
                {
                    Filter = "Images files (*.jpg;*.jpeg;*.png;*.bmp)|*.jpg;*.jpeg;*.png;*.bmp",
                    OverwritePrompt = true,
                    DefaultExt = "jpeg",
                    InitialDirectory = folder,
                    RestoreDirectory = true
                };
                if (dlg.ShowDialog() == true)
                    filePath = dlg.FileName;
            }
            if (string.IsNullOrEmpty(filePath)) return null;
            ImageHelper.Save(filePath, frame);
            return filePath;
        }

        /// <summary>
        /// 保存画图数据到文件
        /// </summary>
        /// <returns></returns>
        public string SaveDrawDataToFile(string drawFilePath = null)
        {
            if (drawCanvas.GetDrawGeometries().Count() == 0)
                return null;

            if (string.IsNullOrEmpty(drawFilePath))
            {
                var dlg = new SaveFileDialog
                {
                    Filter = "XML files (*.xml)|*.xml",
                    OverwritePrompt = true,
                    DefaultExt = "xml",
                    RestoreDirectory = true
                };

                if (dlg.ShowDialog() == true)
                {
                    drawFilePath = dlg.FileName;
                }
            }

            if (!string.IsNullOrEmpty(drawFilePath))
            {
                this.drawCanvas.SaveDrawDataToFile(drawFilePath);
                return drawFilePath;
            }
            return null;
        }

        /// <summary>
        /// 打印
        /// </summary>
        public void Print()
        {
            var backgroundImage = this.drawViewer.BackgroundImage;
            this.drawCanvas.Print(backgroundImage.PixelWidth, backgroundImage.PixelHeight, backgroundImage);
        }

        #endregion
    }
}